package com.contract.spirit.ui.main.first.adapter

import android.content.Context
import com.contract.spirit.bean.entity.BannerInfo
import com.youth.banner.adapter.BannerAdapter
import com.contract.spirit.ui.main.first.adapter.BannerImgAdapter.BannerViewHolder
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.databinding.DataBindingUtil
import android.view.LayoutInflater
import com.contract.spirit.R
import android.util.SparseArray
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.contract.commonlib.util.ext.setOnSingleClickListener
import com.contract.spirit.databinding.AdapterFirstpageBannerItemBinding
import com.contract.spirit.ui.webview.CommonWebViewActivity

class BannerImgAdapter     //设置数据，也可以调用banner提供的方法,或者自己在adapter中实现
    (private val context: Context, mDatas: List<BannerInfo?>?) :
    BannerAdapter<BannerInfo?, BannerViewHolder>(mDatas) {
    //创建ViewHolder，可以用viewType这个字段来区分不同的ViewHolder
    override fun onCreateHolder(parent: ViewGroup, viewType: Int): BannerViewHolder {
        val binding = DataBindingUtil.inflate<ViewDataBinding>(
            LayoutInflater.from(parent.context),
            R.layout.adapter_firstpage_banner_item,
            parent,
            false
        )
        //注意，必须设置为match_parent，这个是viewpager2强制要求的
        binding.root.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        return BannerViewHolder(binding)
    }

    override fun onBindView(
        holder: BannerViewHolder?,
        data: BannerInfo?,
        position: Int,
        size: Int
    ) {
        holder?.getDataBinding<AdapterFirstpageBannerItemBinding>()?.let {
            it.bannerInfo = data
            it.ivBanner.setOnSingleClickListener {
                if (data!!.jumpUrl.isNotBlank()) {
                    CommonWebViewActivity.goLaunch(context, "", data.jumpUrl)
                }
            }
        }
    }


    class BannerViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root) {
        fun <DB : ViewDataBinding?> getDataBinding() = binding as DB

        // 用来存放子View减少findViewById的次数
        private val mViews: SparseArray<View> = SparseArray()

        /**
         * 通过id获取view
         */
        fun <T : View?> getView(viewId: Int): T {
            // 先从缓存中找
            var view: View? = mViews.get(viewId)
            if (view == null) {
                // 直接从ItemView中找
                view = itemView.findViewById(viewId)
                mViews.put(viewId, view)
            }
            return view as T
        }
    }
}